<?php

namespace backend\models;

use common\models\Responses;
use webvimark\helpers\LittleBigHelper;
use Yii;
use webvimark\modules\UserManagement\components\UserIdentity;
use webvimark\modules\UserManagement\components\AuthHelper;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $realname
 * @property string $department
 * @property string $post
 * @property string $is_leader
 * @property string $auth_key
 * @property string $password_hash
 * @property string $confirmation_token
 * @property integer $status
 * @property integer $superadmin
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $registration_ip
 * @property string $bind_to_ip
 * @property string $email
 * @property integer $email_confirmed
 *
 */
class User extends UserIdentity
{


    const STATUS_ACTIVE = 1;
    const STATUS_INACTIVE = 0;
    const STATUS_BANNED = -1;

    /**
     * @var string
     */
    public $gridRoleSearch;

    /**
     * @var string
     */
    public $_department;

    public $_post;

    /**
     * @var string
     */
    public $password;

    /**
     * @var string
     */
    public $repeat_password;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'realname', 'department', 'post'], 'required'],

            [['username', 'realname', 'department', 'post', 'password_hash', 'confirmation_token', 'bind_to_ip'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['registration_ip'], 'string', 'max' => 15],
            [['email'], 'string', 'max' => 128],
            ['avatar', 'default', 'value' => '/image/common/hearder-user.png'],

            ['password', 'required', 'on' => ['newUser', 'changePassword']],
            ['password', 'string', 'max' => 255, 'on' => ['newUser', 'changePassword']],
            ['password', 'trim', 'on' => ['newUser', 'changePassword']],
            ['password', 'match', 'pattern' => Yii::$app->getModule('user-management')->passwordRegexp],

            ['repeat_password', 'required', 'on' => ['newUser', 'changePassword']],
            ['repeat_password', 'compare', 'compareAttribute' => 'password'],
            [['is_leader',], 'safe'],

        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => '登陆名',
            'realname' => '姓名',
            'department' => '部门',
            'post' => '岗位',
            'is_leader' => '是否为部门领导',
            'auth_key' => 'Auth Key',
            'password_hash' => 'Password Hash',
            'confirmation_token' => 'Confirmation Token',
            'status' => 'Status',
            'superadmin' => 'Superadmin',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'registration_ip' => 'Registration Ip',
            'bind_to_ip' => 'Bind To Ip',
            'email' => 'Email',
            'avatar' => '头像',
            'email_confirmed' => 'Email Confirmed',
        ];
    }

    public static function getActiveUsers()
    {
        return ArrayHelper::map(User::find()->select(['id', 'realname'])->where(['status' => 1])->asArray()->all(), 'id', 'realname');
    }

    public function getDepartment()
    {
        return $this->_department;
    }

    public function setDepartment($value)
    {
        $this->_department = trim($value);
    }

    public function getUserDepartment()
    {
        return $this->hasOne(UserDepartment::className(), ['name' => 'department']);
    }

    public function getUserPost()
    {
        return $this->hasOne(UserPost::className(), ['name' => 'post']);
    }

    public function getUserInfo($id)
    {
        $query = (new \yii\db\Query())
            ->select('u.*,d.description  department_desc,p.description post_desc')
            ->from('user u')
            ->leftJoin('auth_item d', 'u.department=d.name')
            ->leftJoin('auth_item p', 'u.post=p.name')
            ->where(['u.id' => $id])
            ->limit(1)
            ->orderBy('id DESC')
            ->one();
        return $query;
    }

    /**
     * @inheritdoc
     * @return UserQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new UserQuery(get_called_class());
    }


    /**
     * @param string $permission
     * @param bool $superAdminAllowed
     *
     * @return bool
     */
    public static function hasPermission($permission, $superAdminAllowed = true)
    {
        if ($superAdminAllowed AND Yii::$app->user->isSuperadmin) {
            return true;
        }

        AuthHelper::ensurePermissionsUpToDate();

        return in_array($permission, Yii::$app->session->get(AuthHelper::SESSION_PREFIX_PERMISSIONS, []));
    }

    /**
     * Make sure user will not deactivate himself and superadmin could not demote himself
     * Also don't let non-superadmin edit superadmin
     *
     * @inheritdoc
     */
    public function beforeSave($insert)
    {
        if ($insert) {
            if (php_sapi_name() != 'cli') {
                $this->registration_ip = LittleBigHelper::getRealIp();
            }
            $this->generateAuthKey();
        } else {
            // Console doesn't have Yii::$app->user, so we skip it for console
            if (php_sapi_name() != 'cli') {
                if (Yii::$app->user->id == $this->id) {
                    // Make sure user will not deactivate himself
                    $this->status = static::STATUS_ACTIVE;

                    // Superadmin could not demote himself
                    if (Yii::$app->user->isSuperadmin AND $this->superadmin != 1) {
                        $this->superadmin = 1;
                    }
                }

                // Don't let non-superadmin edit superadmin
                if (isset($this->oldAttributes['superadmin']) && !Yii::$app->user->isSuperadmin && $this->oldAttributes['superadmin'] == 1) {
                    return false;
                }
            }
        }

        // If password has been set, than create password hash
        if ($this->password) {
            $this->setPassword($this->password);
        }

        return parent::beforeSave($insert);
    }

    /**
     * Useful for Menu widget
     *
     * <example>
     *    ...
     *        [ 'label'=>'Some label', 'url'=>['/site/index'], 'visible'=>User::canRoute(['/site/index']) ]
     *    ...
     * </example>
     *
     * @param string|array $route
     * @param bool $superAdminAllowed
     *
     * @return bool
     */
    public static function canRoute($route, $superAdminAllowed = true)
    {
        if ($superAdminAllowed AND Yii::$app->user->isSuperadmin) {
            return true;
        }

        $baseRoute = AuthHelper::unifyRoute($route);

        if (Route::isFreeAccess($baseRoute)) {
            return true;
        }

        AuthHelper::ensurePermissionsUpToDate();

        return Route::isRouteAllowed($baseRoute, Yii::$app->session->get(AuthHelper::SESSION_PREFIX_ROUTES, []));
    }

    /**
     * getStatusList
     * @return array
     */
    public static function getStatusList()
    {
        return array(
            self::STATUS_ACTIVE => UserManagementModule::t('back', 'Active'),
            self::STATUS_INACTIVE => UserManagementModule::t('back', 'Inactive'),
            self::STATUS_BANNED => UserManagementModule::t('back', 'Banned'),
        );
    }

    /**
     * getStatusValue
     *
     * @param string $val
     *
     * @return string
     */
    public static function getStatusValue($val)
    {
        $ar = self::getStatusList();

        return isset($ar[$val]) ? $ar[$val] : $val;
    }


    /**
     * Don't let delete yourself and don't let non-superadmin delete superadmin
     *
     * @inheritdoc
     */
    public function beforeDelete()
    {
        // Console doesn't have Yii::$app->user, so we skip it for console
        if (php_sapi_name() != 'cli') {
            // Don't let delete yourself
            if (Yii::$app->user->id == $this->id) {
                return false;
            }

            // Don't let non-superadmin delete superadmin
            if (!Yii::$app->user->isSuperadmin AND $this->superadmin == 1) {
                return false;
            }
        }

        return parent::beforeDelete();
    }

    /*
     *  获取某个角色下的所有用户ID
     *
     * @access public
    * @param  $name 角色名称
    * @return array
     */
    public static function getRolesUser($name)
    {
        if (!empty($name)) {
            $userRolesInfo = (new \yii\db\Query())->select('user_id')->from('auth_assignment as aa')->where(['=', 'aa.item_name', $name])->all();
        }
        if (!empty($userRolesInfo)) {
            return json_encode(Responses::response200($userRolesInfo, count($userRolesInfo), '角色ID 查找成功'));
        }
        return json_encode(Responses::response400('无数据 查找失败'));
    }
}
